<?php
namespace App\Admin\Controllers;

use App\Admin\Filters\DemoFilter;
use App\Admin\Models\Demo;
use App\Admin\Models\SystemModel;
use App\Admin\Requests\DemoRequest;
use App\Admin\Resources\DemoResource;
use Illuminate\Support\Facades\Cache;

class DemoController extends Controller
{
    public function store(
        DemoRequest $request, 
        Demo $demo
    ){
        $inputs = $request->validated();
        $token = md5(json_encode($inputs));
        unset($inputs['token']);
        if (Cache::get($token) == 2) {
            return $this->error('请不要重复提交数据');
        } 
        Cache::put($token, 1);
        $demo = $demo->add($inputs);
        Cache::put($token, 2);

        return $this->created(DemoResource::make($demo));
    }

    public function create()
    {
        return $this->ok();
    }

    public function update(
        DemoRequest $request, 
        Demo $demo
    ){
        $inputs = $request->validated();
        $demo->update($inputs);

        return $this->created(DemoResource::make($demo));
    }

    public function edit(Demo $demo)
    {
        return $this->ok(DemoResource::make($demo));
    }
    
    public function destroy(
        Demo $demo
    ){
        $demo->delete();
        return $this->noContent();
    }

    public function index(
        DemoFilter $filter,
        Demo $demo
    ){
        $demos = Demo::withTrashed(isRestore())
            ->filter($filter)
            ->select(SystemModel::getFields($demo->getTable()))
            ->paginate();

        return $this->ok(DemoResource::collection($demos));
    }

    public function show(
        Int $id
    ){
        $demo = Demo::withTrashed(isRestore())
            ->select(SystemModel::getFields(app(Demo::class)->getTable(), 'detail'))
            ->find($id);
        return $this->ok(DemoResource::make($demo));
    }
}
